/*************************************************************************
	> File Name: alarm.c
	> Author: chen
	> Mail: chen_tmacy@foxmail.com
	> Created Time: 2014年12月31日 星期三 10时07分13秒
    > note: 闹钟程序的多线程版本。结构体alarm_t中定义了闹钟的时间和
    >　信息。alarm_thread函数是闹钟线程，主函数创建线程后就会调用该函数
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>

typedef struct alarm_tag{
    int seconds;
    char message[64];
}alarm_t;

void * alarm_thread(void* arg){
    alarm_t * alarm = (alarm_t*) arg;
    int status;

    status = pthread_detach(pthread_self());
    if(0 != status){
        perror("Detach thread");
    }
    sleep(alarm->seconds);
    printf("(%d) %s\n",alarm->seconds,alarm->message);
    free(alarm);
    return NULL;
}


int main(void){
    char line[128];

    int status;
    alarm_t * alarm;
    pthread_t thread;

    while(1){
        printf("Alarm>");
        if(fgets(line,sizeof(line),stdin) == NULL) exit(0);
        if(strlen(line) <= 1) continue;

        alarm = (alarm_t*)malloc(sizeof(alarm_t));
        if(NULL == alarm) exit(0);

        if(sscanf(line,"%d %64[^\n]",&alarm->seconds,alarm->message) < 2 ){
            fprintf(stderr,"Bad command\n");
            free(alarm);
        }else{
            status = pthread_create(&thread,NULL,alarm_thread,alarm);
            if(status != 0){
                perror("creae alarm thread");
            }
        }
    }
    return 0;
}
